package mashibing.class17;

import java.util.Stack;

/**
 * 栈逆序
 */
public class Class17_5_ReverseStackUsingRecursive {

    public static Stack<Integer> reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return stack;
        }
        // 获取栈底元素,并移除
        int i = f(stack);
        reverse(stack);
        stack.push(i);
        return stack;
    }

    // 栈底元素移除掉
    // 上面的元素盖下来
    // 返回移除掉的栈底元素
    private static int f(Stack<Integer> stack) {
        Integer pop = stack.pop();
        if (stack.isEmpty()) {
            return pop;
        } else {
            int f = f(stack);
            stack.push(pop);
            return f;
        }
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        reverse(stack);
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }
}
